package org.arch_learn.servlet_container.components;

import org.arch_learn.servlet_container.components.connector.Connector;
import org.arch_learn.servlet_container.components.connector.Endpoint;
import org.arch_learn.servlet_container.components.container.Engine;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;
import java.util.concurrent.ThreadPoolExecutor;

public class Service extends Thread {
    private Server server;
    private String serviceName;
    private Engine engine;
    private Integer port;
    private ThreadPoolExecutor threadPoolExecutor;

    public Service(Server server, String name, String port, Engine engine, ThreadPoolExecutor threadPoolExecutor) {
        this.server = server;
        this.serviceName = name;
        this.engine = engine;
        this.port = Integer.valueOf(port);
        this.threadPoolExecutor = threadPoolExecutor;
    }

    public Service(Server server, String port, ThreadPoolExecutor threadPoolExecutor) {
        this.server = server;
        this.serviceName = UUID.randomUUID().toString();
        this.engine = new Engine();
        this.port = Integer.valueOf(port);
        this.threadPoolExecutor = threadPoolExecutor;
    }

    public Server getServer() {
        return server;
    }

    public void setServer(Server server) {
        this.server = server;
    }

    public String getServiceName() {
        return serviceName;
    }

    public void setServiceName(String serviceName) {
        this.serviceName = serviceName;
    }

    public Engine getEngine() {
        return engine;
    }

    public void setEngine(Engine engine) {
        this.engine = engine;
    }

    public Integer getPort() {
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }

    public ThreadPoolExecutor getThreadPoolExecutor() {
        return threadPoolExecutor;
    }

    public void setThreadPoolExecutor(ThreadPoolExecutor threadPoolExecutor) {
        this.threadPoolExecutor = threadPoolExecutor;
    }

    @Override
    public void run() {
        try {
            System.out.println("服务:" + serviceName + "正在处理请求---------");
            ServerSocket serverSocket = new ServerSocket(port);
            while (true) {
                Socket socket = serverSocket.accept();
                Endpoint endpoint = new Endpoint(socket);
                Connector connector = new Connector(this, endpoint);
                threadPoolExecutor.execute(connector);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
